# -*- Python -*-

import platform
import os
import subprocess

import lit.formats

# Configuration file for the 'lit' test runner.

###
# Retrieve expected values from lit.site.cfg

llbuild_src_root = getattr(config, 'llbuild_src_root', None)
if llbuild_src_root is None:
    lit_config.fatal("missing 'llbuild_src_root' key in site specific config")
llbuild_obj_root = getattr(config, 'llbuild_obj_root', None)
if llbuild_obj_root is None:
    lit_config.fatal("missing 'llbuild_obj_root' key in site specific config")
llbuild_output_dir = getattr(config, 'llbuild_output_dir', None)
if llbuild_output_dir is None:
    lit_config.fatal("missing 'llbuild_output_dir' key in site specific config")
llbuild_tools_dir = getattr(config, 'llbuild_tools_dir', None)
if llbuild_tools_dir is None:
    lit_config.fatal("missing 'llbuild_tools_dir' key in site specific config")
llbuild_lib_dir = getattr(config, 'llbuild_lib_dir', None)
if llbuild_lib_dir is None:
    lit_config.fatal("missing 'llbuild_lib_dir' key in site specific config")

llbuild_src_root = os.path.normpath(llbuild_src_root)
llbuild_obj_root = os.path.normpath(llbuild_obj_root)
llbuild_tools_dir = os.path.normpath(llbuild_tools_dir)
llbuild_lib_dir = os.path.normpath(llbuild_lib_dir)

###
# Basic Configuration Parameters

# name: The name of this test suite.
config.name = 'llbuild'

# NOTE: this mirrors kIsWindows from lit.lit.TestRunner in LLVM
kIsWindows = platform.system() == 'Windows'

use_lit_shell = os.environ.get('LIT_USE_INTERNAL_SHELL', kIsWindows)
if not use_lit_shell:
    config.available_features.add('shell')

# testFormat: The test format to use to interpret tests.
config.test_format = lit.formats.ShTest(execute_external = False)

# suffixes: A list of file extensions to treat as test files.
#
# We override this in specific subdirectories to change what we test.
config.suffixes = []

# excludes: A list of directories to exclude from the testsuite. The 'Inputs'
# subdirectories contain auxiliary inputs for various tests in their parent
# directories.
config.excludes = ['Inputs']

# test_source_root: The root path where tests are located.
config.test_source_root = os.path.join(llbuild_src_root, 'tests')

# test_source_root: The root path where tests are executing.
config.test_exec_root = os.path.join(llbuild_obj_root, 'tests')

# We don't make use of this yet.
#
# FIXME: This is pretty compiler specific and probably should just be ripped out
# of lit.
config.target_triple = ""

###

# Add a platform feature.
config.available_features.add("platform="+platform.system())

if platform.system() == 'Linux' and 'ANDROID_DATA' not in os.environ:
    with open('/proc/version') as version:
        if 'Microsoft' in version.read():
            config.available_features.add('windows_subsystem_linux')

# Add swiftc feature.
if not config.swiftc_path == "":
  config.available_features.add("has-swift=TRUE")
else:
  config.available_features.add("has-swift=FALSE")

###

def inferSwiftBinary(binaryName):
    # Determine which executable to use
    envVarName = binaryName.upper().replace("-", "_")
    execPath = os.getenv(envVarName)

    # If the user set the variable in the environment, definitely use that and
    # don't try to validate.
    if execPath:
        return execPath

    # Otherwise look in the path.
    PATH = config.environment['PATH']
    execPath = lit.util.which(binaryName, PATH)

    if execPath:
        if not lit_config.quiet:
            lit_config.note('using {}: {}'.format(binaryName, execPath))
    else:
        msg = "couldn't find '{}' program, try setting {} in your environment"
        lit_config.warning(msg.format(binaryName, envVarName))

        # Just substitute the plain executable name, so the run line remains
        # reasonable.
        execPath = binaryName

    return execPath

# Define our supported substitutions.
config.substitutions.append( ('%{llbuild}', "%r" % (
            os.path.join(llbuild_tools_dir, 'llbuild'),)) )
config.substitutions.append( ('%{swift-build-tool}', "%r" % (
            os.path.join(llbuild_tools_dir, 'swift-build-tool'),)) )
config.substitutions.append( ('%{adjust-times}', "%r" % (
            os.path.join(llbuild_tools_dir, 'adjust-times'),)) )
config.substitutions.append( ('%{FileCheck}', config.filecheck_path) )
config.substitutions.append( ('%{swiftc}', config.swiftc_path) )
config.substitutions.append( ('%{llbuild-lib-dir}', llbuild_lib_dir) )
config.substitutions.append( ('%{llbuild-output-dir}', llbuild_output_dir) )
config.substitutions.append( ('%{llbuild-tools-dir}', llbuild_tools_dir) )
config.substitutions.append( ('%{srcroot}', llbuild_src_root) )

if config.osx_sysroot:
    config.substitutions.append( ('%{swiftc-platform-flags}', "-sdk " + config.osx_sysroot) )
else:
    config.substitutions.append( ('%{swiftc-platform-flags}', "") )

config.substitutions.append( ('%{build-dir}', llbuild_obj_root) ) 
config.substitutions.append( ('%{env}', lit.util.which('env')) )
config.substitutions.append( ('%{sort}', lit.util.which('sort')) )
config.substitutions.append( ('%{sh-invoke}', os.environ.get("PREFIX", "") + '/bin/sh') )
config.substitutions.append( ('%clang', inferSwiftBinary('clang')) )

###

# Always propagate HOME.
config.environment["HOME"] = os.environ.get("HOME", "")

# Propagate LLVM_PROFILE_FILE if used.
llvm_profile_file = os.environ.get("LLVM_PROFILE_FILE")
if llvm_profile_file:
    config.environment["LLVM_PROFILE_FILE"] = llvm_profile_file

# Protected against unquoted use of substitutions.
for name in ('llbuild', 'FileCheck'):
  config.substitutions.append((' {0} '.format(name),
                               ' unquoted-command-name-{0} '.format(name)))
